import request from "../request";
import storage from "../storage";
import util from "../util";

let result = {};
/**
 * 获取当前语言编码
 * @returns {*} 语言编码
 */
result.getLanguageCode = function () {
    if (storage.get("languageCode")) {
        return storage.get("languageCode");
    }
    let languageCode = uni.getSystemInfoSync().osLanguage
        || uni.getSystemInfoSync().language
        || uni.getSystemInfoSync().hostLanguage.split("-")[0]
        || "en-US";
    languageCode = languageCode.replace("-", "_");
    return languageCode;
}

/**
 * 设置当前语言编码
 * @param languageCode 语言编码
 */
result.setLanguageCode = function (languageCode) {
    // 是否存在语言本地化，如果存在就设置成语言本地化中的语言编码
    let dictI18nLocalizedMap = storage.get("dictI18nLocalizedMap");
    if (!dictI18nLocalizedMap) {
        storage.set("languageCode", languageCode);
        return;
    }
    if (dictI18nLocalizedMap[languageCode]) {
        storage.set("languageCode", dictI18nLocalizedMap[languageCode]);
        return;
    }
    storage.set("languageCode", languageCode);
}

/**
 * 获取语言本地化
 */
result.loadingLocalized = function () {
    return new Promise((resolve, reject) => {
        request.send({
            uri: "/system-language-web/language/getLocalizedList",
            stateSuccess: (res) => {
                console.debug("获取语言本地化成功", res.data);
                // 将语言本地化存储到本地
                storage.set("dictI18nLocalizedList", res.data);
                console.info("获取语言本地化", res.data);
                // 转换为map存储
                let dictI18nLocalizedMap = {};
                res.data.forEach((item) => {
                    dictI18nLocalizedMap[item.code] = item.languageCode;
                });
                storage.set("dictI18nLocalizedMap", dictI18nLocalizedMap);
                result.setLanguageCode(result.getLanguageCode());
                resolve(res.data);
            },
            stateFail: (res) => {
                // uni.showToast({
                //     title: "获取语言本地化错误：" + res.errMsg,
                //     icon: "none"
                // })
                reject();
            }
        });
    });
}

/**
 * 加载所有支持的语言
 */
result.loadingSupportLanguage = function () {
    return new Promise((resolve, reject) => {
        request.send({
            uri: "/system-language-web/language/getBySupport",
            stateSuccess: (res) => {
                console.debug("获取所有支持的语言成功", res.data);
                // 将所有支持的语言存储到本地
                storage.set("dictI18nSupportLanguageList", res.data);
                let languageMap = {};
                for (let i = 0; i < res.data.length; i++) {
                    languageMap[res.data[i].code] = res.data[i].name;
                }
                storage.set("dictI18nLanguageMap", languageMap);

                resolve(res.data);
            },
            stateFail: (res) => {
                reject();
            }
        });
    });
}

/**
 * 获取当前语言
 */
result.getLanguageName = function (languageCode) {
    try {
        let languageMap = storage.get("dictI18nLanguageMap");
        if (languageMap[languageCode]) {
            return languageMap[languageCode];
        }
        return languageCode;
    } catch (e) {
        return languageCode;
    }
}


/**
 * 获取所有支持的语言
 */
result.getSupportLanguage = function () {
    return storage.get("dictI18nSupportLanguageList");
}



/**
 * 加载语言包
 */
result.loadLanguagePackage = function (dictGroupCode, languageCode) {
    // 如果languageCode为空，则获取当前语言编码
    if (!languageCode) {
        languageCode = result.getLanguageCode();
    }

    return new Promise((resolve, reject) => {
        request.post("/system-dict-web/dict/getDict", { data: { dictGroupCode } }).then(res => {
            console.debug("加载字典包成功", res.data);
            let topKey = "SysDict";
            // 获取 centerKeys
            let centerKeys = [];
            for (let i = 0; i < res.data.length; i++) {
                centerKeys.push(res.data[i].fullCode);
            }
            request.post("/system-language-web/languageI18n/getList",
                {
                    data: {
                        languageCode,
                        topKey,
                        centerKeys
                    }
                }).then(res1 => {
                    let json = res1.data;
                    console.debug("加载语言包成功", json);
                    storage.set("dictI18nList_" + dictGroupCode + "_" + languageCode, json);
                    let dictI18nMap = {};
                    json.forEach((item) => {
                        dictI18nMap[item.centerKey] = item.content;
                    });
                    storage.set("dictI18nMap_" + dictGroupCode + "_" + languageCode, dictI18nMap);
                    // 如果是中文，就存储到本地
                    if (languageCode === "zh_CN") {
                        let dictI18nMap2 = {};
                        json.forEach((item) => {
                            dictI18nMap2[item.content] = item.centerKey;
                        });
                        storage.set("dictI18nZhToGlobal_"+dictGroupCode, dictI18nMap2);
                    }
                    // 如果是英文，就存储到本地
                    if (languageCode === "en_US") {
                        let dictI18nMap2 = {};
                        json.forEach((item) => {
                            dictI18nMap2[item.content] = item.centerKey;
                        });
                        storage.set("dictI18nEnToGlobal_"+dictGroupCode, dictI18nMap2);
                    }

                    resolve(json);
                }).catch(err => {
                    console.debug("加载字典包失败", err);
                    reject(err);
                });
        }).catch(err => {
            console.debug("加载字典包失败", err);
            reject(err);
        });
    });
}

/**
 * 中文包转为全局
 * @param value 值
 * @param dictGroupCode 字典组编码
 * @returns {*}
 */
result.zhToGlobal = function (value, dictGroupCode) {
    if (!dictGroupCode) {
        dictGroupCode = "appFront";
    }
    try {
        let key = storage.get("dictI18nZhToGlobal_"+dictGroupCode)[value];
        let newVar = storage.get("dictI18nMap_" + dictGroupCode + "_" + result.getLanguageCode())[key];
        return util.firstLetterUpper(newVar);
    } catch (e) {
        return value;
    }
}

/**
 * 英文包转全局
 * @param value 值
 * @param dictGroupCode 字典组编码
 */
result.enToGlobal = function (value, dictGroupCode) {
    if (!dictGroupCode) {
        dictGroupCode = "appFront";
    }
    try {
        let key = storage.get("dictI18nEnToGlobal_"+dictGroupCode)[value];
        let newVar = storage.get("dictI18nMap_" + dictGroupCode + "_" + result.getLanguageCode())[key];
        return util.firstLetterUpper(newVar);
    } catch (e) {
        return util.firstLetterUpper(value);
    }
}

/**
 * 获取对应国际化的集合
 */
result.getI18n =  (data) => {
    return new Promise((resolve,reject) => {
        let map = {};
        request.send({
            uri: "/system-language-web/languageI18n/getList",
            data: {
                ...data,
                languageCode: result.getLanguageCode()
            },
            stateSuccess: (res) => {
                for (let i = 0; i < res.data.length; i++) {
                    const item = res.data[i];
                    map[item.centerKey] = item;
                }
                console.debug("获取国际化成功", map);
                let resData = {list: res.data, map: map};
                resolve(resData);
            },
            stateFail: (res) => {
                console.debug("获取国际化失败", res);
                reject(res);
            }
        })
    });
}


export default result;


